import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Modal,
  message,
  Badge,
  Divider,
  Tag,
  InputNumber,
  Popconfirm
} from 'antd';
import StandardTable from 'components/StandardTableN';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './Category.less';

const FormItem = Form.Item;
const formItemLayout = { labelCol: { span: 4 }, wrapperCol: { span: 10 } }

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleOk, handleCancel, record, loading } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      handleOk(fieldsValue, form);
    });
  };
  return (
    <Modal
      title={(record && record.catId) ? "编辑类目" : '添加类目'}
      visible={modalVisible}
      confirmLoading={loading}
      onOk={okHandle}
      onCancel={() => handleCancel(false, form)}
    >
      {
        (record && record.catId) ?
          <FormItem {...formItemLayout} label="id" style={{ display: 'none' }}>
            {form.getFieldDecorator('catId', {
              rules: [{ required: true, message: '请输入id' }],
              initialValue: record ? record.catId : null,
            })(<Input placeholder="请输入ID" />)}
          </FormItem>
          :
          null
      }
      <FormItem {...formItemLayout} label="类目名称">
        {form.getFieldDecorator('catName', {
          rules: [{ required: true, message: '类目名称不能为空' }],
          initialValue: record ? record.catName : null,
        })(<Input placeholder="请输入名称" maxLength={4} />)}
      </FormItem>

      <FormItem {...formItemLayout} label="权重">
        {form.getFieldDecorator('weight', {
          rules: [{ required: true, message: '权重不能为空' }],
          initialValue: record ? record.weight : null,
        })(<InputNumber min={0} step={1} precision={0} placeholder="请输入权重" style={{ width: '100%' }} />)}
      </FormItem>
    </Modal>
  );
});

@connect(({ category, loading }) => ({
  category,
  categoryList: category.categoryList,
  loading: loading.models.category,
}))
@Form.create()
export default class Category extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    record: null,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'category/fetchCategoryList',
    });
  }

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();

    dispatch({
      type: 'category/fetchCategoryList',
      payload: {},
    });
  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch() {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      dispatch({
        type: 'category/fetchCategoryList',
        payload: values,
      });
    });
  };

  _setModalVisible(flag, record) {
    if (!flag) {
      this.setState({
        record: null,
        modalVisible: flag,
      })
    } else {
      this.setState({
        record: record,
        modalVisible: flag,
      })
    }
  }

  _handleOk = (fields, form) => {
    const { dispatch } = this.props;
    if (fields.catId) {
      dispatch({
        type: 'category/editCategory',
        payload: fields,
        callback: () => { this._setModalVisible(false, null); this.handleSearch(); form.resetFields(); }
      });
    } else {
      dispatch({
        type: 'category/addCategory',
        payload: fields,
        callback: () => { this._setModalVisible(false, null); this.handleSearch(); form.resetFields(); }
      });
    }
  };

  _handleCancel(flag, form) {
    this._setModalVisible(flag);
    form.resetFields();
  }

  _deleteCategory() {
    if (this.state.selectedRows.length > 0) {
      let catIdList = [];
      for (let i = 0; i < this.state.selectedRows.length; i++) {
        catIdList.push(this.state.selectedRows[i].catId)
      }
      this.props.dispatch({
        type: 'category/deleteCategory',
        payload: { catIdList: catIdList },
        callback: () => { this.handleSearch(); this.setState({ selectedRows: [] }) }
      });
    }
  }

  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="类目名称">
              {getFieldDecorator('catName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this.handleSearch()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { categoryList, loading, } = this.props;
    const { selectedRows, modalVisible } = this.state;

    const tableData = {}
    tableData['list'] = categoryList;

    const columns = [
      {
        title: '类目名称',
        dataIndex: 'catName',
        key: 'catName',
      },
      {
        title: '权重',
        dataIndex: 'weight',
        key: 'weight',
      },
      {
        title: '操作',
        key: '操作',
        render: (text, record) => (
          <Fragment>
            <a onClick={() => this._setModalVisible(true, record)}>编辑</a>
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this._setModalVisible(true, null)}>
                新建
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Popconfirm title="确定要删除选中的类目吗?" placement="bottom" onConfirm={() => this._deleteCategory()} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="danger" icon="delete" >
                      删除
                  </Button>
                  </Popconfirm>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={tableData}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              page={"no"}
              rowKey="catId"
            />
          </div>
        </Card>
        <CreateForm handleOk={(fieldsValue, form) => this._handleOk(fieldsValue, form)} modalVisible={modalVisible}
          handleCancel={(flag, form) => this._handleCancel(flag, form)} record={this.state.record} loading={this.props.loading}
        />
      </PageHeaderLayout>
    );
  }
}
